package models;

import play.db.jpa.*;
import javax.persistence.*;
import play.db.jpa.Transactional;
import play.data.validation.Constraints.*;
import at.ac.tuwien.big.we14.lab2.api.User;
import play.Logger;
import java.util.List;
import java.util.ArrayList;
import play.data.validation.ValidationError;
import play.i18n.Messages;

@Entity
public class Player implements User {

	public enum Gender {
		m("m"),
		f("f");

		private final String name;   

		private Gender(String s) {
			name = s;
		}

		public boolean equalsName(String otherName){
			return (otherName == null)? false:name.equals(otherName);
		}

		public String toString() {
			return name;
		}
	}

	public String firstname;
	public String lastname;
	//@TODO Date validation
	public java.util.Date birthdate;
	public Gender gender;
	@Id
	public String username;
	public String password;

	public List<ValidationError> validate() {
		List<ValidationError> errors = new ArrayList<ValidationError>();
		if (username == null || username.isEmpty()) {
			errors.add(new ValidationError("username", Messages.get("registration.error.requirement", Messages.get("registration.username"))));
		} else if (username.length() < 4 || username.length() > 8) {
			errors.add(new ValidationError("username", Messages.get("registration.error.minmax", Messages.get("registration.username.art") + " " + Messages.get("registration.username"), 4, 8)));
		} else if (Player.findByUsername(username) != null) {
			errors.add(new ValidationError("username", Messages.get("regsitration.error.username", username)));
		}
		if (password == null || password.isEmpty()) {
			errors.add(new ValidationError("password", Messages.get("registration.error.requirement", Messages.get("registration.password"))));
		} else if (password.length() < 4 || password.length() > 8) {
			errors.add(new ValidationError("password", Messages.get("registration.error.minmax", Messages.get("registration.password.art") + " " + Messages.get("registration.password"), 4, 8)));
		} 

		return errors.isEmpty() ? null : errors;
	}
	@Override
	public String getName() {
		return this.username;
	}

	@Override
	public void setName(String name) {
		this.username = name;
	}

	@Transactional
	public void save() {
		JPA.em().persist(this);
	}
	
	@Transactional(readOnly=true)
	public static Player findByUsername(String username) {
		if (username == null) { return null; }
		return JPA.em().find(Player.class, username);
	}

	@Transactional(readOnly=true)
	public static Player authenticate(String username, String password) {
		Player player = JPA.em().find(Player.class, username);
		if (player != null && player.password.equals(password)) {
			Logger.info("Autentification of " + player.username + " with password " + player.password);
			Logger.info("player " + player.firstname + " found");
			return player;
		}
		Logger.info("player not found");
		return null;
	}
}
